package main

import (
	"latencyPublisher/pkg/k8sClient"
	"latencyPublisher/pkg/ping"
	"os"
	"os/signal"
	"strconv"
	"syscall"

	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"k8s.io/client-go/kubernetes"
)

func main() {
	// 生成停止channel
	stopCh := make(chan os.Signal, 1)
	signal.Notify(stopCh, syscall.SIGTERM, syscall.SIGINT)

	rootCmd := &cobra.Command{
		Use: "latencyPublisher",
		Run: func(cmd *cobra.Command, args []string) {
			var kubernetesCient *kubernetes.Clientset
			var err error
			var nodeName string

			if cmd.Flag("inCluster").Value.String() == "false" {
				kubernetesCient, err = k8sClient.NewOutsideClusterClientSet("")
				nodeName = cmd.Flag("nodeName").Value.String()
			} else {
				kubernetesCient, err = k8sClient.NewInsideClusterClientSet()
			}
			if err != nil {
				logrus.Errorf("[main]-创建clienset失败")
				return
			}

			// 获取nodeName
			if nodeName == "" {
				nodeName = os.Getenv("NODE_NAME")
			}

			// 获取启动mode
			// 1. crd - publisher向crd更新数据
			// 2. prometheus - publisher向prometheus更新数据
			mode := cmd.Flag("mode").Value.String()
			exporterPortStr := cmd.Flag("exporterPort").Value.String()
			exporterPort, err := strconv.Atoi(exporterPortStr)
			if err != nil {
				logrus.Errorf("[main]-解析exporterPort失败: %v", err)
				return
			}
			publisher := ping.NewLatencyPublisher(kubernetesCient, nodeName, mode, exporterPort)
			err = publisher.Initialize()
			if err != nil {
				logrus.Error("[main]-初始化publisher失败")
				return
			}

			publisher.Run()

			<-stopCh
			// 可以在这里进行一些清理逻辑
		},
	}

	bindFlags(rootCmd)

	if err := rootCmd.Execute(); err != nil {
		logrus.Errorf("[main.go]-rootCmd执行失败")
		return
	}
}

func bindFlags(command *cobra.Command) {
	command.Flags().BoolP("inCluster", "i", false, "whether this program runs in K8s cluster(default false)")
	command.Flags().StringP("mode", "m", "crd", "the mode of latency publisher, can be 'crd' or 'prometheus'")
	command.Flags().StringP("exporterPort", "", "8080", "the port of prometheus exporter, only works in 'prometheus' mode")
}
